package com.hmdp.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IShopTypeService typeService;

    @Override
    public Result queryTypeList() {
        // 1.从redis查询商铺类型缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        List<ShopType> cacheShop1 = JSONUtil.toList(cacheShop, ShopType.class);
        // 2.判断是否存在
        if(cacheShop1.size() !=0){
            // 3. 存在
            return Result.ok(cacheShop1);
        }
        // 4.不存在,根据ID查询数据库
        List<ShopType> shopTypes = typeService.query().orderByAsc("sort").list();
        // 5.不存在，返回错误
        if(shopTypes.size() == 0){
            return Result.fail("店铺不存在！");
        }
        // 6.存在，写入redis
        String shop1 = JSONUtil.toJsonStr(shopTypes);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, shop1);
        return Result.ok(shopTypes);
    }
}
